public class Test {

    //任意位置插入
    public void addIndex(int index,int data) {
        int len = size();
        if(index < 0 || index > size()) {
            throw new IndexOutOfBoundsException("双向链表index位置不合法: "+index);
        }
        if(index == 0) {
            addFirst(data);
            return;
        }
        if(index == size()) {
            addLast(data);
            return;
        }

        ListNode node = new ListNode(data);
        ListNode cur = Findindex(index);

        node.next = cur;
        cur.prev.next = node;
        node.prev = cur.prev;
        cur.prev = node;
    }

    //寻找插入节点的后一个节点
    public ListNode findindex(int index) {
        ListNode cur = head;
        while(index != 0) {
            cur = cur.next;
            index--;
        }
        return cur;
    }

    //头插法
    public void addFirst(int data) {
        ListNode node = new ListNode(data);

        if(head == null) {
            head = node;
            last = node;
        }else {
            node.next = head;
            head.prev = node;
            head = node;
        }
    }

    //尾插法
    public void addLast(int data) {
        ListNode node = new ListNode(data);

        if(head == null) {
            head = node;
            last = node;
        }else {
           last.next = node;
           node.prev = last;
           last = node;
        }
    }
}
